//
//  CSNValidator.m
//  HPZZTong
//
//  Created by WenJun on 14-7-16.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "CSNValidator.h"
#import "HPSwiperService.h"
#import "ZZTongClientEngine.h"
#import "HPClientEngine.h"
#import "CategoryUtil.h"

#define CSNChecker [CSNValidator sharedInstance]

static CSNValidator * singleton = nil;

@interface CSNValidator()<NetCallBackDelegate>
{
    SwiperComplete _block;
    BOOL _tip;
    BOOL _networkUnAvailable;
}

@property (nonatomic) BOOL running;

@property (strong,nonatomic) NSString * location;

@property (strong,nonatomic) NSString * address;

@property (strong,nonatomic) NSDate * locationDate;

@end

@implementation CSNValidator

+ (CSNValidator *)sharedInstance
{
    if (!singleton)
    {
        singleton = [[super allocWithZone:NULL] init];
    }
    return singleton;
}

+ (void)validateCSNAndExcuteBlock:(SwiperComplete)block autoTip:(BOOL)tip
{
    [CSNChecker validateCSNAndExcuteBlock:block autoTip:tip];
}

+ (void)checkCSNStatus:(SwiperComplete)block autoTip:(BOOL)tip
{
    if (SwiperService.csn && ![NSString isNilOrEmpty:ZZT_CLIENG.accountInfo.account])
    {
        [CSNChecker checkCSNStatus:block autoTip:tip];
    }
}

- (void)validateCSNAndExcuteBlock:(SwiperComplete)block autoTip:(BOOL)tip
{
    _running = YES;
    _block = block;
    _tip = tip;
    [SwiperService checkAndConnectSwiper:^(HPSwiperResult *result) {
        if (result.isSuccess)
        {
            if ([NSString isNilOrEmpty:ZZT_CLIENG.accountInfo.account])
            {
                [self finishedWithErrMsg:@"用户未登录"];
            }
            else
            {
                [self checkCSNStatus:_block autoTip:_tip];
            }
        }else if(result.code == HPSwiperResultLowBattery){
            [self finishedWithErrMsg:TipsLowBattery];
        }
        else if (!result.isCanceld)
        {
            [self finishedWithErrMsg:@"请插入刷卡器"];
        }
    }];
}
+ (void)clearData{
    [singleton clearData];
}
- (void)clearData{
    _networkUnAvailable = NO;
    _running = NO;
    _block = nil;
    _tip = NO;
}
- (void)checkCSNStatus:(SwiperComplete)block autoTip:(BOOL)tip
{
    _running = YES;
    _block = block;
    _tip = tip;
    
    if (![HPUIENG doCheckGPSStatus])
    {
        [self finishedWithErrMsg:LocationErrMsg2];
        return;
    }
    if (!_networkUnAvailable)
    {
        _networkUnAvailable = YES;
        [HPUIENG showWaiting:@"正在加载中..."];
        [HPUIENG getAddressWithGPSBlock:^(NSString *latitude, NSString *longitude, NSString *address, NSError *error) {
            if (latitude.length > 0 && longitude.length > 0 && address.length > 0)
            {
                LOG(@"%@ %@ %@",latitude,longitude,address);
                _location = [NSString stringWithFormat:@"%@,%@",latitude,longitude];
                _address = address;
                _locationDate = [NSDate date];
                
            }
            if (!SwiperService.csn)
            {
                _tip = NO;
                [self finishedWithErrMsg:@"刷卡器已断开"];
                return;
            }
            if (_locationDate && -[_locationDate timeIntervalSinceNow] < 1200)//20分钟内 可以使用上次的获取的位置
            {
                NSDictionary* params = @{KEY_ACCOUNT : DES_ENC(ZZT_CLIENG.accountInfo.account),
                                         KEY_CSN : DES_ENC(SWIPERENG.csn),
                                         KEY_ADDRESS : _address,
                                         KEY_LOCATION: [CSNValidator getLocation],
                                         KEY_CHANNEL : [ZZT_CLIENG getChannel]};
                [ZZT_CLIENG.netEngine sendRequest:NET_ACTION_ZZT_GET_SWIPER_STATUS withParams:params withDelegate:self withAddress:APP_URL_NAME withAlertFlag:NO];
            }
            else
            {
                [HPUIENG removeWaiting];
                _networkUnAvailable = NO;
                AlertCommandData* commandCancel = [[AlertCommandData alloc]initCommand:@"取消" function:@selector(cancelLocation)];
                AlertCommandData* commandOK = [[AlertCommandData alloc]initCommand:@"再次获取" function:@selector(retryLocation)];
                AlertData* alertData = [[AlertData alloc] initAlertData:self title:@"提示" message:@"获取地理位置失败，请至信号良好处再次获取。" commands:commandCancel,commandOK, nil];
                [HPUIENG showAlertWithData:alertData];
            }
        }];
    }
}

- (void)retryLocation
{
    [self checkCSNStatus:_block autoTip:_tip];
}

- (void)cancelLocation
{
    _tip = NO;//定位失败不提示
    [self finishedWithErrMsg:LocationErrMsg];
}

+ (NSString *)getLocation
{
    return CSNChecker.location;
}

+ (NSString *)getAddress
{
    return CSNChecker.address;
}

- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respDat
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [HPUIENG removeWaiting];
        if ([action isEqualToString:NET_ACTION_ZZT_GET_SWIPER_STATUS])
        {
            [self configStatusResponse:respDat];
        }else if ([action isEqualToString:NET_ACTION_ZZT_BIND_SWIPER]){
            [self parseBindSwiper:respDat];
        }
        _networkUnAvailable = NO;
    });
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg
{
    if ([action isEqualToString:NET_ACTION_ZZT_GET_SWIPER_STATUS])
    {   [HPUIENG removeWaiting];
        if (msg.length > 0)
        {
            [self finishedWithErrMsg:msg];
        }
        else
        {
            [self finishedWithErrMsg:@"请求刷卡器状态失败"];
        }
    }
    _networkUnAvailable = NO;
}

- (void)configStatusResponse:(NSDictionary *)respData
{
    NSString * status = [respData objectForKey:@"status"];
    NSString * msg = nil;
    if (status.length > 0)
    {
        msg = [respData objectForKey:@"message"];
        if ([status isEqualToString:@"0"]){
            [SwiperService setCsnStatus:CSNStatusAvailable];
            msg = nil;
        }else if ([status isEqualToString:@"1"]){
            [SwiperService setCsnStatus:CSNStatusUnbound];
            msg = nil;
        }else if ([status isEqualToString:@"2"]){
            [SwiperService setCsnStatus:CSNStatusBoundOtherUser];
        }else if ([status isEqualToString:@"3"]){
            [SwiperService setCsnStatus:CSNStatusBoundOtherChannel];
        }else if ([status isEqualToString:@"4"]){
            [SwiperService setCsnStatus:CSNStatusLoss];
        }else if ([status isEqualToString:@"5"]){
            [SwiperService setCsnStatus:CSNStatusLogOut];
        }else{
            [SwiperService setCsnStatus:CSNStatusNone];
        }
    }
    else
    {
        msg = [respData objectForKey:NET_ERROR_MESSAGE];
        if([NSString isNilOrEmpty:msg]){
            msg = [respData objectForKey:@"message"];
        }
    }
    if ([NSString isNilOrEmpty:msg])
    {
        msg = [self tipsFromCsnStatus];
    }
    [self finishedWithErrMsg:msg];
}

- (void)finishedWithErrMsg:(NSString *)msg
{
    _networkUnAvailable = NO;
    _running = NO;
    HPSwiperResult * result = nil;
    if (msg)
    {
        if (_tip)
        {
            [HPUIENG showAlert:msg];
        }
        result = [[HPSwiperResult alloc] initWithCode:HPSwiperResultFail message:msg value:[NSNumber numberWithInteger:SwiperService.csnStatus]];
    }
    else
    {
        result = [HPSwiperResult successResult:nil];
    }
    ExecuteSwiperBlock(_block,result);
    _block = nil;
}

- (NSString *)tipsFromCsnStatus
{
    if (SwiperService.csnStatus == CSNStatusAvailable)
    {
        return nil;
    }
    if (SwiperService.csnStatus == CSNStatusLogOut)
    {
        return @"刷卡器已注销";
    }
    if (SwiperService.csnStatus == CSNStatusLoss)
    {
        return @"刷卡器已挂失";
    }
    if (SwiperService.csnStatus == CSNStatusBoundOtherChannel)
    {
        return @"刷卡器已绑定到其他渠道";
    }
    if (SwiperService.csnStatus == CSNStatusBoundOtherUser)
    {
        return @"刷卡器已绑定到其他用户";
    }
    if (SwiperService.csnStatus == CSNStatusUnbound)
    {
        if (_tip)//资质提交过程中不提示绑定刷卡器或者资质未提交，有资质提交按钮的页面也不提示
        {
            Screen* screen = [HPUIENG getCurrentScreen];
            if ([screen.screenName isEqualToString:SCR_REGISTER_SUCCESS]||
                [screen.screenName isEqualToString:SCR_QUALITY_CONFIRM] ||
//                [screen.screenName isEqualToString:SCR_ACCOUNT_INDEX] ||
                [screen.screenName isEqualToString:SCR_QUALITY_INDEX] ||
                [screen.screenName isEqualToString:SCR_QUALITY_PHOTO] ||
                [screen.screenName isEqualToString:SCR_REVIEW_STATE]) {
                _tip = NO;
            }
        }

        if (ZZT_CLIENG.accountInfo.accountStatus != AccountStatusNotSubmit)
        {
            if (_tip)
            {
                AlertCommandData* commandCancel = [[AlertCommandData alloc] initCommand:@"取消" function:@selector(doCancel)];
                AlertCommandData* commandBind = [[AlertCommandData alloc] initCommand:@"绑定" function:@selector(doBindCSN)];
                AlertData* alertData = [[AlertData alloc] initAlertData:self title:@"提示" message:@"刷卡器未绑定，需要立即绑定吗？" commands:commandCancel, commandBind, nil];
                [HPUIENG showAlertWithData:alertData];
                _block = nil;
                _tip = NO;
            }
            return @"刷卡器未绑定";
        }
        else
        {
            _tip = NO;//不提示资质未提交
            if (_tip)
            {
                AlertCommandData* commandCancel = [[AlertCommandData alloc]initCommand:@"暂不提交"];
                AlertCommandData* commandOK = [[AlertCommandData alloc]initCommand:@"马上提交" function:@selector(submitQuality)];
                
                AlertData* alertData = [[AlertData alloc] initAlertData:ZZT_CLIENG title:@"提示" message:@"资质信息未提交" commands:commandOK,commandCancel, nil];
                [HPUIENG showAlertWithData:alertData];
                _block = nil;
                _tip = NO;
            }
            return @"未提交资质信息";
        }
    }
    return @"刷卡器状态未知";
}
- (void)doCancel{
    
}
- (void)doBindCSN:(NSString*)csn{
    
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    [zzt.uiEngine showNetWaiting];
    
    NSString* tempCsn = csn;
    if ([NSString isNilOrEmpty:tempCsn]) {
        tempCsn = SwiperService.csn;
    }
    
    NSDictionary* params = @{KEY_CHANNEL : [zzt getChannel],
                             KEY_PHONE : DES_ENC(ZZT_CLIENG.accountInfo.mobile),
                             KEY_CSN : DES_ENC(tempCsn),
                             @"account":DES_ENC(zzt.accountInfo.account)};
    [zzt.netEngine sendRequest:NET_ACTION_ZZT_BIND_SWIPER withParams:params withDelegate:self];
}
- (void)parseBindSwiper:(NSDictionary *)respData{
    if ([[respData objectForKey:NET_RESPONSE_CODE]isEqualToString:NET_RESPONSE_SUCCESS]){
        [HPUIENG showAlert:@"绑定成功"];
        [SwiperService setCsnStatus:CSNStatusNone];
        [CSNValidator checkCSNStatus:nil autoTip:NO];
    }
}
- (void)doBindCSN{
    [self doBindCSN:SwiperService.csn];
}
+ (void)bindCSN:(NSString*)csn{
    [CSNChecker doBindCSN:csn];
}
+ (BOOL)isRunning
{
    return CSNChecker.running;
}


@end
